package com.xunmall.gateway.security;


import com.xunmall.account.service.impl.JCaptchaServiceImpl;
import com.xunmall.base.constants.SecurityConstants;
import com.xunmall.base.util.NumberUtils;
import com.xunmall.base.util.WebUtils;
import com.xunmall.security.GlobalSessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpointAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * @author fanjun
 * @date 2017/6/28
 */
@Slf4j
public class SecurityTokenEndpointAuthenticationFilter extends TokenEndpointAuthenticationFilter {

    public SecurityTokenEndpointAuthenticationFilter(AuthenticationManager authenticationManager, OAuth2RequestFactory oAuth2RequestFactory) {
        super(authenticationManager, oAuth2RequestFactory);
    }

    @Override
    protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String remoteAddr = WebUtils.getRemoteAddr(request);
        String sessionId = remoteAddr;
        GlobalSessionUtil.removeLoginProfile(sessionId);
        response.setHeader("jcaptchaNeed", "false");
    }

    @Override
    protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {
        String remoteAddr = WebUtils.getRemoteAddr(request);
        String sessionId = remoteAddr;

        Object failureCount = GlobalSessionUtil.getLoginProfile(sessionId, SecurityConstants.CODE_JCAPTCHA_NEED);
        int count = 0;
        if (failureCount != null) {
            count = NumberUtils.getIntValue(failureCount);
        }
        GlobalSessionUtil.setLoginProfile(sessionId, SecurityConstants.CODE_JCAPTCHA_NEED, ++count, 60 * 3);
        Boolean jcaptchaNeed = JCaptchaServiceImpl.getJcaptchaEbabled(sessionId);
        response.setHeader("jcaptchaNeed", jcaptchaNeed.toString());
    }
}